#include "ft_event.h"
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


void work_cb(void* ptr)
{
    LOG_ENTER_FN;
    ev_stream_del((ev_stream_t*)ptr);
}

void async_cb(void* ptr)
{
    LOG_ENTER_FN;

    LOG("async job cb tid = %d", pthread_self());

    ev_job_t job;
    job.ptr = ptr;
    job.cb = work_cb;

    ev_thread_pool_post(ev_default_thread_pool(), &job);
}


int async_tiemr_cb(void* ptr)
{

    ev_job_t job;
    ev_timer_t* timer;

    ev_async_t* c;

    timer = (ev_timer_t*)ptr;
    c = (ev_async_t*)timer->data;

    LOG("async_tiemr_cb %d %d", c->ev->cur_thread, pthread_self());

    bzero((void*)&job, sizeof(ev_job_t));
    job.ptr = c;
    job.cb = async_cb;
    ev_async_post(c, &job);

    timer->repeat = 0;

    free(timer);

    return 1;
}


int pre_run(ev_server_t* server)
{
    ev_config_t* config = ev_default_config();

    if(config->max_nthread >= 2 ) {
        ev_timer_t* async_timer = (ev_timer_t*)malloc(sizeof(ev_timer_t));
        ev_async_t* async_channel = ev_async_new(server->evloop[0]);

        async_timer->data = (void*)async_channel;
        async_timer->job.ptr = (void*)async_timer;
        async_timer->job.cb = async_tiemr_cb;

        ev_timer_mgr_start_timer(server->evloop[1]->timer_mgr, async_timer, 2000, 1);
    }

    return 0;
}


int main(int argc, char* argv[])
{
    int opt;
    char* config_path = NULL;

    while((opt=getopt(argc, argv, "f:")) != -1) {
        switch (opt) {
        case 'f':
            config_path = optarg;
            break;
        default:
            break;
        }
    }

    ev_server_run(config_path, pre_run);

    return 0;
}
